/**
 * created by uu, 16/07/15
 * #                                                   #
 * #                       _oo0oo_                     #
 * #                      o8888888o                    #
 * #                      88" . "88                    #
 * #                      (| -_- |)                    #
 * #                      0\  =  /0                    #
 * #                    ___/`---'\___                  #
 * #                  .' \\|     |# '.                 #
 * #                 / \\|||  :  |||# \                #
 * #                / _||||| -:- |||||- \              #
 * #               |   | \\\  -  #/ |   |              #
 * #               | \_|  ''\---/''  |_/ |             #
 * #               \  .-\__  '-'  ___/-. /             #
 * #             ___'. .'  /--.--\  `. .'___           #
 * #          ."" '<  `.___\_<|>_/___.' >' "".         #
 * #         | | :  `- \`.;`\ _ /`;.`/ - ` : | |       #
 * #         \  \ `_.   \_ __\ /__ _/   .-` /  /       #
 * #     =====`-.____`.___ \_____/___.-`___.-'=====    #
 * #                       `=---='                     #
 * #     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   #
 * #                                                   #
 * #               佛祖保佑         永无BUG            #
 * #                                                   #
 */
package com.hemaapp.yjnh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseFragment;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.activity.BuyConfirmActivityNew;
import com.hemaapp.yjnh.activity.CmnProductionDetailActivity;
import com.hemaapp.yjnh.bean.Cart;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.cart.ShoppingCartAdapter;
import com.hemaapp.yjnh.cart.TouchableRecyclerView;
import com.hemaapp.yjnh.listener.CartListener;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 购物车
 */
public class ShoppingCartFragment extends BaseFragment implements CartListener {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.ckbx_all)
    CheckBox ckbxAll;
    @Bind(R.id.tv_total_fee)
    TextView tvTotalFee;
    @Bind(R.id.btn_pay)
    Button btnPay;
    @Bind(R.id.layout_bottom)
    RelativeLayout layoutBottom;
    @Bind(R.id.refreshLoadmoreLayout)
    RefreshLoadmoreLayout layoutRefresh;
    @Bind(R.id.recycler_cart)
    TouchableRecyclerView recyclerCart;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.layout_login)
    LinearLayout layoutLogin;

    private User user;
    private Double totalPrice = 0.00;
    private ArrayList<Cart.ChildItem> selectedItems = new ArrayList<Cart.ChildItem>();//已经勾选的商品
    private ArrayList<Cart.ChildItem> cartChildren = new ArrayList<>();
    DecimalFormat df = new DecimalFormat("#0.00");//保留两位小数
    private ShoppingCartAdapter adapter;
    private Cart.ChildItem cartItemTemp;//修改和删除商品时使用
    private boolean canBack = false;//返回按钮是否显示
    private boolean goAway = false;//是否已经立刻当前Fragment，应对点击进入商品详情的情况

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_shopping_cart);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shopping_cart, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onResume() {
        goAway = false;
        super.onResume();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        user = BaseApplication.getInstance().getUser();
        Bundle bundle = getArguments();
        if (bundle != null)
            canBack = bundle.getBoolean("back");
        initViews();
        layoutRefresh.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                tvTotalFee.setText("合计：¥0.00元");
                ckbxAll.setChecked(false);
                if (getNetWorker() == null) {
                    layoutRefresh.refreshFailed();
                    return;
                }
                getNetWorker().cartList(user.getToken());
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {

            }
        });
        layoutRefresh.setLoadmoreable(false);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerCart.setLayoutManager(layoutManager);
    }

    private void initViews() {
        titleText.setText("购物车");
        titleRightBtn.setText("清空");
        if (canBack)
            titleLeftBtn.setVisibility(View.VISIBLE);
        else {
            titleLeftBtn.setVisibility(View.GONE);
        }
        if (user != null) {
            layoutRefresh.setVisibility(View.VISIBLE);
            layoutLogin.setVisibility(View.GONE);
            getNetWorker().cartList(user.getToken());
        }else {
            layoutLogin.setVisibility(View.VISIBLE);
            layoutRefresh.setVisibility(View.GONE);
            titleRightBtn.setEnabled(false);
            btnPay.setEnabled(false);
            ckbxAll.setEnabled(false);
        }
    }

    @Override
    protected void findView() {

    }

    @Override
    protected void setListener() {
    }

    /**
     * 刷新全部费用
     */
    public void setTotalFee() {
        totalPrice = 0.0;
        for (int i = 0; i < selectedItems.size(); i++) {
            Cart.ChildItem childItem = selectedItems.get(i);
            double price = Double.valueOf(childItem.getPrice());
            double count = 1;
            String countStr = childItem.getBuycount();
            if (countStr != null) {
                count = Double.valueOf(countStr);
            }
            totalPrice += price * count;
        }
        tvTotalFee.setText("合计：¥"+df.format(totalPrice) + "元");
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CART_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CART_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CART_LIST:
                String page = netTask.getParams().get("page");
                HemaArrayResult<Cart> cResult = (HemaArrayResult<Cart>) baseResult;
                layoutRefresh.refreshSuccess();
                if (cResult.getObjects() == null || cResult.getObjects().size() == 0) {
                    titleRightBtn.setEnabled(false);
                    btnPay.setEnabled(false);
                    ckbxAll.setEnabled(false);
                } else {
                    titleRightBtn.setEnabled(true);
                    btnPay.setEnabled(true);
                    ckbxAll.setEnabled(true);
                }
                ckbxAll.setChecked(false);
                cartChildren.clear();
                selectedItems.clear();
                for (Cart cart : cResult.getObjects()) {
                    ArrayList<Cart.ChildItem> items = cart.getChildItems();
                    cartChildren.addAll(items);
                }
                refreshData();
                break;
            case CART_SAVEOPERATE:
                //1：单个删除 ；2：清空购物车 ；3：更改购买计数 ；4：清空过期购物车
                String type = netTask.getParams().get("keytype");
                if ("2".equals(type)) {
                    XtomToastUtil.showShortToast(getActivity(), "清空成功");
                    titleRightBtn.setEnabled(false);
                    btnPay.setEnabled(false);
                    ckbxAll.setChecked(false);
                    ckbxAll.setEnabled(false);
                    tvTotalFee.setText("合计：¥0.00元");
                    ckbxAll.setChecked(false);
                    getNetWorker().cartList(user.getToken());
                }else if ("1".equals(type)) {//删除
                    adapter.notifyItemRemoved(cartChildren.indexOf(cartItemTemp));
                    cartChildren.remove(cartItemTemp);
                    cartItemTemp = null;
                    adapter.notifyDataSetChanged();
                    setTotalFee();//重新计算总价
                }else if ("3".equals(type)) {//修改数量
                    String count = netTask.getParams().get("buycount");
                    cartItemTemp.setBuycount(count);
                    setTotalFee();//刷新全部费用
                }
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_CART);
                EventBus.getDefault().post(msg);
                break;
            default:
                break;
        }
    }

    private void refreshData() {
        if (adapter == null) {
            adapter = new ShoppingCartAdapter(getActivity(), cartChildren);
            adapter.setListener(this);
            recyclerCart.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CART_LIST:
                refreshData();
                XtomToastUtil.showShortToast(getActivity(), "获取信息失败，" + baseResult.getMsg());
                break;
            case CART_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作失败，" + baseResult.getMsg());
                //1：单个删除 ；2：清空购物车 ；3：更改购买计数 ；4：清空过期购物车
                String type = netTask.getParams().get("keytype");
                if (type.equals("3")) {
                    cartItemTemp.setBuycount(cartItemTemp.getBuycount());
                    adapter.notifyDataSetChanged();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CART_LIST:
                refreshData();
                XtomToastUtil.showShortToast(getActivity(), "获取信息失败，请检查网络");
                break;
            case CART_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作失败,请稍后再试");
                //1：单个删除 ；2：清空购物车 ；3：更改购买计数 ；4：清空过期购物车
                String type = netTask.getParams().get("keytype");
                if (type.equals("3")) {
                    cartItemTemp.setBuycount(cartItemTemp.getBuycount());
                    adapter.notifyDataSetChanged();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void modifyGoodsCount(Cart.ChildItem item, String count) {
        cartItemTemp = item;
        if (!count.equals(item.getBuycount())) {
            getNetWorker().cartSaveoperate(user.getToken(), item.getId(), "3", count);
        }
    }

    @Override
    public void deleteCartItem(Cart.ChildItem item) {
        cartItemTemp = item;
        adapter.closeOpenedSwipeItemLayoutWithAnim();
        if (selectedItems.contains(item))
            selectedItems.remove(item);
        getNetWorker().cartSaveoperate(user.getToken(), item.getId(), "1", "0");
    }

    @Override
    public void onItemClickListener(Cart.ChildItem item) {
        goAway = true;
        Intent itDtl = new Intent(getActivity(), CmnProductionDetailActivity.class);
        itDtl.putExtra("blog_id", item.getKeyid());
        startActivity(itDtl);
    }

    @Override
    public void onHeaderClickListener(String headerId) {
        for (Cart.ChildItem item : cartChildren) {
            if (item.getSeller_id().equals(headerId)) {
                boolean sellerCheck = !item.isSellerChecked();
                item.setChecked(sellerCheck);
                item.setSellerChecked(sellerCheck);
                if (sellerCheck) {//让子类全选
                    if (!selectedItems.contains(item))
                        selectedItems.add(item);
                    if (selectedItems.size() >= cartChildren.size())
                        ckbxAll.setChecked(true);
                } else {
                    selectedItems.remove(item);
                    ckbxAll.setChecked(false);
                }
            }
        }
        adapter.notifyDataSetChanged();
        setTotalFee();
    }

    @Override
    public void onItemCheckChangedListener(Cart.ChildItem item, boolean checked) {
        item.setChecked(checked);
        if (checked) {
            selectedItems.add(item);
        } else {
            selectedItems.remove(item);
        }
        checkMerchant(item.getSeller_id());
        adapter.notifyDataSetChanged();
        setTotalFee();
    }

    /**
     * 判断所属商家中的商品是否已经全选
     */
    private void checkMerchant(String sellerId) {
        boolean isAll = true;
        for (Cart.ChildItem item : cartChildren) {
            if (item.getSeller_id().equals(sellerId) && !item.isChecked()) {//如果该商家下，有商品未选中
                isAll = false;
                break;
            }
        }
        //设置该商家下的商品属性
        for (Cart.ChildItem item : cartChildren) {
            if (item.getSeller_id().equals(sellerId))
                item.setSellerChecked(isAll);
        }
        if (isAll)//如果该商家全选，再去判断是否所有商家全选
            checkAll();
        else
            ckbxAll.setChecked(false);
    }

    /**
     * 判断是否购物车中全部商品已经勾选
     */
    public void checkAll() {
        boolean isAll = true;
        for (Cart.ChildItem item : cartChildren) {
            if (!item.isSellerChecked()) {
                isAll = false;
                break;
            }
        }
        if (isAll) {//如果已经全选，就把全选按钮勾上
            ckbxAll.setChecked(true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_btn, R.id.ckbx_all, R.id.btn_pay, R.id.btn_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                if (canBack)
                    getActivity().finish();
                break;
            case R.id.title_right_btn:
                HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
                hbDialog.setText("确定清空全部购物车?");
                hbDialog.setLeftButtonText("取消");
                hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                hbDialog.setRightButtonText("确定");
                hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        getNetWorker().cartSaveoperate(user.getToken(), "无", "2", "0");
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.ckbx_all:
                boolean allCheck = selectedItems.size() >= cartChildren.size() ? true : false;
                for (Cart.ChildItem item : cartChildren) {
                    item.setChecked(!allCheck);
                    item.setSellerChecked(!allCheck);
                }
                selectedItems.clear();
                if (!allCheck) {//如果之前不是全选
                    selectedItems.addAll(cartChildren);
                }
                adapter.notifyDataSetChanged();
                setTotalFee();
                break;
            case R.id.btn_pay:
                if (selectedItems.size() == 0) {
                    XtomToastUtil.showShortToast(getActivity(), "请至少选择一件商品");
                    return;
                }
                goAway = true;
                Intent itBuy = new Intent(getActivity(), BuyConfirmActivityNew.class);
                itBuy.putExtra("keytype", "1");//1：从购物车中来 2：立即购买 3：定制订单 4：走走订单
                itBuy.putExtra("cart", selectedItems);
                startActivity(itBuy);
                break;
            case R.id.btn_login:
                BaseUtil.checkLogin(getActivity());
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            initViews();
        }else if (msg.getType() == EventBusConfig.UPDATE_CART && (isHidden() || goAway)) {//只有购物车在后台的时候才刷新
            tvTotalFee.setText("合计：¥0.00元");
            ckbxAll.setChecked(false);
            getNetWorker().cartList(user.getToken());
        }
    }
}
